<template>
  <view class="app-layout">
    <!-- <app-header></app-header> -->
    <view class="app-main">
      <app-sider pageKey="setting" />
      <view class="app-content">
        <view class="navbar-con">
          <view class="navbar-bar">
            <view v-for="(tab, index) in tabList" :key="index" class="tab-item" :class="{ active: currentTab == index }"
              @click="handlecurrentTab(index)">
              {{ tab }}
            </view>
          </view>
        </view>
        <view class="developed-wrap" v-if="currentTab!=3">
          <view class="developed-con">
            <image src="@/static/imgs/developed.png" mode=""></image>
            <text>功能正在开发中…</text>
          </view>
        </view>
        <view class="tabs-wrapper" v-if="currentTab==3">
          <u-tabs :list="tabListAll" @click="tabClick1" :scrollable="true" keyName="name"
            :activeStyle="{ color: '#0F90FD', fontWeight: '500', fontSize: '16px' }">
            <template #content="{ item, keyName, index }">
              <view style="position: relative">
                {{ item[keyName] }}
                <u-badge type="error" max="99" :value="item.num" :absolute="true" :offset="[-10, -25]"></u-badge>
              </view>
            </template>
          </u-tabs>
        </view>
        <view class="goods-wrapper" v-if="currentTab==3">
          <view class="code-form" v-if='formType==0'>
            <view class="tit">
              门店信息
            </view>
            <u-form labelPosition="left" labelWidth="110px" :model="storeForm" ref="storeFormRef">
              <view class="form-info">
                <u-form-item label="门店ID">
                  <view class="box">
                    <uni-easyinput placeholder="请输入门店ID" v-model="storeForm.storeId" :disabled="true"
                      clearable></uni-easyinput>
                  </view>
                </u-form-item>

                <u-form-item label="门店名称">
                  <view class="box">
                    <uni-easyinput placeholder="请输入门店名称" type="text" v-model="storeForm.storeName"
                      :disabled="!isstoreEditing.storeName" :disableColor="'#eee'" clearable
                      @blur="handleStoreInputBlur('storeName')"></uni-easyinput>
                  </view>
                 <!-- <image src="/static/imgs/edit.png" mode="" @click="startStoreEditing('storeName')" class="edit-icon">
                  </image> -->
                </u-form-item>

                <u-form-item label="经营时间">
                  <view class="box">
                    <uni-easyinput placeholder="例如：09:00-22:00" type="text" v-model="storeForm.businessHours"
                      :disabled="!isstoreEditing.businessHours" clearable
                      @blur="handleStoreInputBlur('businessHours')"></uni-easyinput>
                  </view>
                 <!-- <image src="/static/imgs/edit.png" mode="" @click="startStoreEditing('businessHours')"
                    class="edit-icon">
                  </image> -->
                </u-form-item>
                <u-form-item label="门店地址">
                  <view class="box">
                    <uni-easyinput placeholder="请输入详细地址" type="text" v-model="storeForm.address"
                      :disabled="!isstoreEditing.address" clearable
                      @blur="handleStoreInputBlur('address')"></uni-easyinput>
                  </view>
                  <!--   <image src="/static/imgs/edit.png" mode="" @click="startStoreEditing('address')" class="edit-icon">
                  </image> -->
                <!--  <image src="/static/imgs/edit.png" mode="" @click="getCurrentLocation('address')" class="edit-icon">
                  </image> -->
                </u-form-item>
              </view>
            </u-form>
          </view>
          <view class="code-form" v-if='formType==1'>
            <view class="tit">
              配送规则
            </view>
            <u-form labelPosition="left" labelWidth="110px" :model="formData" ref="refFrom">
              <view class="form-info">
                <!--               <u-form-item label="是否外送">
                  <u-switch v-model="formData.isActive" size="20" :activeValue="1" :inactiveValue="0"
                    activeColor="#20D048" @change="handleSwitchChange"></u-switch>
                </u-form-item>
                <u-form-item label="配送时段">
                  <view class="box">
                    <uni-easyinput placeholder="请输入" v-model="formData.deliveryTime" :disabled="!isEditing.deliveryTime"
                      clearable @blur="handleInputBlur('deliveryTime')"></uni-easyinput>
                  </view>
                  <image src="/static/imgs/edit.png" mode="" @click="startEditing('deliveryTime')" class="edit-icon">
                  </image>
                </u-form-item>
                <u-form-item label="起送价">
                  <view class="box">
                    <uni-easyinput placeholder="请输入" type="digit" v-model="formData.minPrice"
                      :disabled="!isEditing.minPrice" clearable @blur="handleInputBlur('minPrice')">
                      <template #right>
                        <text class="suffix-txt">元</text>
                      </template>
                    </uni-easyinput>
                  </view>
                  <image src="/static/imgs/edit.png" mode="" @click="startEditing('minPrice')" class="edit-icon">
                  </image>
                </u-form-item>
                <u-form-item label="免费配送门槛">
                  <view class="box">
                    <uni-easyinput placeholder="请输入" type="digit" v-model="formData.freeDeliveryThreshold"
                      :disabled="!isEditing.freeDeliveryThreshold" clearable
                      @blur="handleInputBlur('freeDeliveryThreshold')">
                      <template #right>
                        <text class="suffix-txt">元</text>
                      </template>
                    </uni-easyinput>
                  </view>
                  <image src="/static/imgs/edit.png" mode="" @click="startEditing('freeDeliveryThreshold')"
                    class="edit-icon"></image>
                </u-form-item>
                <u-form-item label="计费模式">
                  <view class="box">
                    <u-radio-group v-model="formData.feeMode" placement="row" :disabled="!isEditing.feeMode"
                      @change="handleRadioChange('feeMode')">
                      <u-radio :customStyle="{marginRight: '8px'}" v-for="(item, index) in radiolist1" :key="index"
                        :label="item.name" :name="item.name"></u-radio>
                    </u-radio-group>
                  </view>
                  <image src="/static/imgs/edit.png" mode="" @click="startEditing('feeMode')" class="edit-icon"></image>
                </u-form-item> -->
                <u-form-item label="计费模式">
                  <view class="box">
                    <u-radio-group v-model="formData.feeMode" placement="row">
                      <u-radio :customStyle="{marginRight: '8px'}" v-for="(item, index) in radiolist1" :key="index"
                        :label="item.name" :name="item.name"></u-radio>
                    </u-radio-group>
                  </view>
                </u-form-item>
                <u-form-item label="固定费用">
                  <view class="box">
                    <uni-easyinput placeholder="请输入" type="digit" v-model="formData.fixedFee"
                      :disabled="!isEditing.fixedFee" clearable @blur="handleInputBlur('fixedFee')">
                      <template #right>
                        <text class="suffix-txt">元</text>
                      </template>
                    </uni-easyinput>
                  </view>
                  <image src="/static/imgs/edit.png" mode="" @click="startEditing('fixedFee')" class="edit-icon">
                  </image>
                </u-form-item>
              </view>
            </u-form>
          </view>

          <view class="code-form" v-if='formType==2'>
            <view class="tit">
              退款码设置
            </view>
            <view class="code-con">
              <view class="label">
                退款确认码
              </view>
              <view class="box">
                <uni-easyinput placeholder="请输入" type="text" v-model="refundCode.code" :disabled="dis" clearable
                  @change="submit"></uni-easyinput>
              </view>
              <image src="/static/imgs/edit.png" mode="" @click="handelEdit"></image>
            </view>

          </view>
        </view>
      </view>
    </view>
  </view>

</template>
<script setup>
  import {
    ref,
    computed,
    nextTick,
    reactive,
  } from 'vue'
  import {
    onLoad,
    onShow
  } from '@dcloudio/uni-app'
  import {
    getRefundCodeList,
    updateRefundCode,
    getDeliveryRulesList,
    updateDeliveryRules,
    addDeliveryRules
  } from '@/requests/apis/setting'
  let refundCode = ref()
  let dis = ref(true)
  let currentTab = ref(3)
  let formType = ref(0)
  // let tabList = ref([ '系统配置'])
  let tabList = ref(['用户管理', '角色管理', '操作日志', '系统配置'])
  const tabListAll = ref([{
      name: '门店信息'
    },
    {
      name: '配送规则'
    },
    {
      name: '退款码设置'
    },
    // {
    //   name: '小票机设置'
    // },
  ])
  const formData = reactive({
    id: '',
    isActive: 1,
    deliveryTime: '',
    minPrice: '',
    freeDeliveryThreshold: '',
    feeMode: '固定费用',
    fixedFee: ''
  });

  // 编辑状态管理：每个字段独立控制
  const isEditing = reactive({
    isActive: false,
    deliveryTime: false,
    minPrice: false,
    freeDeliveryThreshold: false,
    feeMode: false,
    fixedFee: false
  });
  // 门店表单数据
  const storeForm = reactive({
    storeId: '',
    storeName: '',
    businessHours: '',
    address: ''
  });

  // 编辑状态管理
  const isstoreEditing = reactive({
    storeId: false,
    storeName: false,
    businessHours: false,
    address: false
  });

  // 计费模式选项
  const radiolist1 = ref([{
      name: '固定费用'
    },
    // {
    //   name: '阶梯计费'
    // },
    // {
    //   name: '重量计费'
    // }
  ]);

  let storeInfo = ref()

  onLoad(() => {

  })
  onShow(async () => {
    let res = uni.getStorageSync("storeInfo")
    storeInfo.value = res
    storeForm.storeId = storeInfo.value.deptId
    storeForm.storeName = storeInfo.value.deptName
    storeForm.address = storeInfo.value.storeAddress
    storeForm.storeLatlng = storeInfo.value.storeLatlng
    storeForm.businessHours = storeInfo.value.openTime + '-' + storeInfo.value.closeTime
  })
  // 获取退款码
  const getRefundCode = async () => {
    let res = await getRefundCodeList({
      deptId: storeInfo.value.deptId
    })
    refundCode.value = res.Result
    dis.value = true
  }
  // 获取配送
  const getDelivery = async () => {
    let res = await getDeliveryRulesList({
      deptId: storeInfo.value.deptId
    })
    formData.id = res.Result.id || undefined
    formData.fixedFee = res.Result.deliveryFee || undefined
  }
  const tabClick1 = (e) => {
    console.log(e, '11111111111')
    if (e.index == 1) {
      getDelivery()
    } else if (e.index == 2) {
      getRefundCode()
    }
    formType.value = e.index
  }
  const handlecurrentTab=(index)=>{
    currentTab.value=index
  }
  const getCurrentLocation = () => {
    const [latStr, lngStr] = storeForm.storeLatlng.split(',');
    uni.chooseLocation({
      latitude: latStr,
      longitude: lngStr,
      success(res) {
        console.log(res, 'rrrrrrrr')
        storeForm.address = res.address
        storeForm.storeLatlng = res.latitude + ',' + res.longitude
      },
      fail(err) {}
    })
  }
  // 配送费
  // 点击编辑图标：激活当前项的编辑状态
  const startEditing = (field) => {
    Object.keys(isEditing).forEach(key => {
      isEditing[key] = false;
    });
    isEditing[field] = true;
  };

  // 切换开关后保存
  const handleSwitchChange = async () => {
    await saveField('isActive', formData.isActive);
  };

  // 输入框失焦后保存
  const handleInputBlur = async (field) => {
    const value = (formData[field] + '').trim();
    // 判断内容是否为空
    if (!value) {
      uni.showToast({
        title: getPlaceholderText(field),
        icon: 'none'
      });
      // 关闭编辑状态
      isEditing[field] = false;
      return;
    }
    if (field === 'deliveryTime' && !validateBusinessHours(value)) {
      uni.showToast({
        title: '请输入正确格式（例如：09:00-22:00）',
        icon: 'none'
      });
      isEditing[field] = false;
      return;
    }
    // 固定费用单独校验
    if (field === 'fixedFee') {
      const validateResult = validateFixedFee(value);
      if (!validateResult.valid) {
        uni.showToast({
          title: validateResult.message,
          icon: 'none'
        });
        isEditing[field] = false;
        return;
      }
      const numberValue = parseFloat(validateResult.formattedValue);
      await saveField(field, numberValue);
      formData[field] = numberValue;
      isEditing[field] = false;
      return;
    }
    await saveField(field, value);
  };

  // 固定费用校验函数
  const validateFixedFee = (value) => {
    // 转换为数字
    const num = Number(value);
    // 校验是否为有效数字
    if (isNaN(num)) {
      return {
        valid: false,
        message: '请输入有效的数字'
      };
    }
    // 校验不能为0或负数
    if (num <= 0) {
      return {
        valid: false,
        message: '固定费用不能为0'
      };
    }
    // 校验小数位数（最多两位）
    const decimalPart = value.split('.')[1] || '';
    if (decimalPart.length > 2) {
      return {
        valid: false,
        message: '最多允许两位小数'
      };
    }
    // 格式化保留两位小数（如：100 → 100.00，12.5 → 12.50）
    const formattedValue = num.toFixed(2);
    return {
      valid: true,
      formattedValue
    };
  };


  // 单选框变更后保存
  const handleRadioChange = async (field) => {
    await saveField(field, formData[field]);
  };

  // 通用保存方法
  const saveField = async (field, value) => {
    try {
      // 显示加载中
      uni.showLoading({
        title: '保存中...'
      });
      let fun = formData.id ? updateDeliveryRules : addDeliveryRules
      let res = await fun({
        [field]: value,
        id: formData.id,
        deptId: storeInfo.value.deptId,
        type: 0
      })

      if (res.ResponseCode == 1) {
        uni.showToast({
          title: res.Result,
          icon: 'success'
        });
      } else {
        uni.showToast({
          title: res.Result,
          icon: 'none'
        });
      }
    } catch (err) {
      console.error('保存失败：', err);
      uni.showToast({
        title: '网络错误',
        icon: 'none'
      });
    } finally {
      // 无论成功失败，都关闭编辑状态（恢复禁用）
      isEditing[field] = false;
      uni.hideLoading();
    }
  };
  // 门店信息设置
  // 点击编辑
  const startStoreEditing = (field) => {
    Object.keys(isstoreEditing).forEach(key => {
      isstoreEditing[key] = false;
    });
    isstoreEditing[field] = true;
  };

  // 输入框失焦处理
  const handleStoreInputBlur = async (field) => {
    const value = (storeForm[field] + '').trim();

    // 空值校验
    if (!value) {
      uni.showToast({
        title: getPlaceholderText(field), // 动态提示文字
        icon: 'none'
      });
      // 关闭编辑状态
      isstoreEditing[field] = false;
      return;
    }
    if (field === 'businessHours' && !validateBusinessHours(value)) {
      uni.showToast({
        title: '请输入正确格式（例如：09:00-22:00）',
        icon: 'none'
      });
      isstoreEditing[field] = false;
      return;
    }
    // 调用保存接口
    await savestoreField(field, value);
  };
  // 验证时间格式（HH:MM-HH:MM）
  const validateBusinessHours = (value) => {
    const reg = /^([01]\d|2[0-3]):([0-5]\d)-([01]\d|2[0-3]):([0-5]\d)$/;
    return reg.test(value);
  };
  // 保存字段（调用接口）
  const savestoreField = async (field, value) => {
    try {
      uni.showLoading({
        title: '保存中...'
      });

      // 实际项目中替换为你的接口
      const res = await uni.request({
        url: '/api/store/update',
        method: 'POST',
        data: {
          [field]: value,
          // 其他必要参数（如门店ID等）
        }
      });

      if (res.data.code === 200) {
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        });
      } else {
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    } catch (err) {
      console.error('保存失败：', err);
      uni.showToast({
        title: '网络错误',
        icon: 'none'
      });
    } finally {
      isEditing[field] = false;
      uni.hideLoading();
    }
  };

  // 动态获取提示文字
  const getPlaceholderText = (field) => {
    const placeholderMap = {
      deliveryTime: "请输入配送时段",
      minPrice: "请输入起送价",
      freeDeliveryThreshold: "请输入起送价免费配送门槛",
      fixedFee: "请输入固定费用",
      storeName: '请输入门店名称',
      businessHours: '请输入经营时间',
      address: '请输入门店地址'
    };
    return placeholderMap[field] || '请输入内容后再保存';
  };
  const handelEdit = () => {
    dis.value = false
  }
  const submit = () => {
    if (refundCode.value.code) {
      // 校验是否包含中文（包括中文标点等）
      const hasChinese = /[\u4e00-\u9fa5]/.test(refundCode.value.code);
      if (hasChinese) {
        uni.showToast({
          title: '退款码不能包含中文',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      updateRefundCode({
        id: refundCode.value.id,
        code: refundCode.value.code
      }).then((res) => {
        if (res.ResponseCode == 1) {
          uni.showToast({
            title: res.Result,
            icon: 'success'
          });
          getRefundCode()
        }
      })
    } else {
      uni.showToast({
        title: '请填写退款码',
        icon: 'none',
        duration: 2000,
      });
    }
  };
</script>

<style lang="scss" scoped>
  .tabs-wrapper {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-around;
    height: 44px;
    background: #fff;
    margin: 10px;

    :deep(.u-tabs) {
      width: 100% !important;

      .u-tabs__wrapper__nav__item {
        flex: 1 !important;
      }

      .u-tabs__wrapper__nav__item__text {
        white-space: nowrap;
      }
    }
  }

  .goods-wrapper {
    display: flex;
    flex: 1;
    overflow: hidden;
  }

  .code-form {
    width: 100%;
    background: #ffffff;
    border-radius: 10px;
    margin: 10px 10px 0;
    padding: 26px 0;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;

    .tit {
      font-weight: 500;
      font-size: 14px;
      color: #333333;
      line-height: 20px;
      margin-left: 20px;
    }

    :deep(.u-form) {
      margin: 30px auto;
    }

    .form-info {
      .box {
        width: 350px;
      }

      .suffix-txt {
        background: #f5f6f8;
        border-left: 1px solid #e8ecef;
        font-weight: 400;
        font-size: 14px;
        color: #334681;
        padding: 6px 16px;
        box-sizing: border-box;
      }

      image {
        width: 16px;
        height: 16px;
        margin-left: 11px;
      }
    }

    .code-con {
      display: flex;
      justify-content: center;
      margin-top: 30px;
      align-items: center;

      .label {
        margin-right: 19px;
        font-weight: 400;
        font-size: 14px;
        color: #333333;
      }

      .box {
        width: 350px;
      }

      image {
        width: 16px;
        height: 16px;
        margin-left: 11px;
      }
    }
  }
</style>
